package cn.qingfeng.nio.notblocking;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioClient {

    public static void main(String[] args) throws IOException {
        // 打开一个Socket通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8080));
        socketChannel.configureBlocking(false);

        // 准备要发送的数据
        String message = "Hello, NIO Server!";
        ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());

        // 发送数据到服务器
        while (buffer.hasRemaining()) {
            socketChannel.write(buffer);
        }

        // 准备接收来自服务器的响应
        while (true) {
            buffer.clear();
            int bytesRead = socketChannel.read(buffer);

            // 非阻塞模式下不能直接取值，要循环判断读到的数据是否为空
            if (bytesRead == -1) {
                System.out.println("连接已关闭");
                break;
            } else if (bytesRead == 0) {
                System.out.println("服务端还没有回应，稍等一会儿……");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            } else {
                System.out.println("读到了数据，开始处理：");
                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                String response = new String(bytes);

                System.out.println("Received response from server: " + response);

                break;
            }
        }

        // 关闭通道
        socketChannel.close();
    }
}